import axios from 'axios'

const list= {
  namespaced: true,
  state: {
    todolist:[]
  },
  mutations: {
    update(state,res) {
      state.todolist = res
    },
    //删除
    del(state,id) {
      state.todolist = state.todolist.filter(x=>x.id!==id) 
    },
    //全选
    all(state) {
      state.todolist.forEach(x => {
        x.isDone =!x.isDone
      })
    },
    //清除已完成
    delitem(state,id) {
      state.todolist = state.todolist.filter(x=>x.id!==id) 
    },
    //已完成
    over(state, list) {
      // console.log(list);
     
      state.todolist = list.filter(x=>x.isDone==true) 
    },
    //进行中
    now(state, list) {
      // console.log(list);
      state.todolist = list.filter(x=>x.isDone==false) 
    },
  },
  actions: {
    //获取
    async getlist(cxt) {
      let res =  await axios.get('http://localhost:3000/list')
      cxt.commit('update', res.data)
      console.log(res);
    },
    //添加数据
    async addlist(cxt, data) {
      await axios({
          method: 'post',
          url: `http://localhost:3000/list/`,
          data
      })
      cxt.dispatch('getlist')
    },
    //删除
    async dellist(cxt, id) {
      await axios({
          method: 'delete',
          url: `http://localhost:3000/list/${id}`,
      })
      cxt.commit('del', id)
    },
    //全反
    async isall(cxt) {
       await axios.get('http://localhost:3000/list')
      cxt.commit('all')
      
    },
    async tick(cxt, item) {
      await axios({
          method: 'patch',
          url: `http://localhost:3000/list/${item.id}`,
          data: {
              isDone: !item.isDone
          }
      })
      cxt.dispatch('getlist')
    },
    //清除已完成
   clearlist(cxt, list) {
      list.forEach( async x => {
        if (x.isDone) {
          await axios({
            method: 'delete',
            url: `http://localhost:3000/list/${x.id}`,
        })
        cxt.commit('delitem', x.id)
        }
      })
      
    },
   //已完成
    async overlist(cxt) {
      let res =  await axios.get('http://localhost:3000/list')
      cxt.commit('update', res.data)
      await axios.get('http://localhost:3000/list')
      cxt.commit('over', res.data)
      
     
    
    },
   //进行中
    async nowlist(cxt) {
      let res =  await axios.get('http://localhost:3000/list')
      cxt.commit('update', res.data)
      await axios.get('http://localhost:3000/list')
      cxt.commit('now', res.data)
    //  console.log(list);
     
  }
  }
}
export default list